// 活动数据相关API服务
import axios from 'axios';
import { API_BASE_URL, axiosConfig, formatDateForApi } from './config';
import api from './auth'; // 导入auth.js中已配置的api实例

// 创建axios实例
const apiClient = axios.create(axiosConfig);

// 模拟的用户数据
const mockUsers = [
  {
    user_id: 'user001',
    nickname: '跑步达人',
    avatar_url: 'https://placekitten.com/100/100',
    gender: '男',
    location: '北京',
    follower_count: 320,
    following_count: 86,
    post_count: 157,
    created_at: '2022-05-12 14:32:00'
  },
  {
    user_id: 'user002',
    nickname: '骑行一族',
    avatar_url: 'https://placekitten.com/100/101',
    gender: '男',
    location: '上海',
    follower_count: 245,
    following_count: 42,
    post_count: 98,
    created_at: '2022-06-03 09:15:00'
  },
  {
    user_id: 'user003',
    nickname: '游泳健将',
    avatar_url: 'https://placekitten.com/101/100',
    gender: '女',
    location: '广州',
    follower_count: 178,
    following_count: 35,
    post_count: 76,
    created_at: '2022-04-18 16:45:00'
  },
  {
    user_id: 'user004',
    nickname: '健身狂人',
    avatar_url: 'https://placekitten.com/102/102',
    gender: '男',
    location: '深圳',
    follower_count: 412,
    following_count: 120,
    post_count: 203,
    created_at: '2021-12-05 11:30:00'
  },
  {
    user_id: 'user005',
    nickname: '瑜伽爱好者',
    avatar_url: 'https://placekitten.com/103/103',
    gender: '女',
    location: '杭州',
    follower_count: 289,
    following_count: 75,
    post_count: 124,
    created_at: '2022-02-14 15:20:00'
  }
];

// 模拟的活动数据 - 扩展数据集
const mockActivities = [
  {
    activity_id: 'a001',
    user_id: 'user001',
    type: '跑步',
    distance: 5.2,
    duration: 1800,
    calorie: 320,
    start_time: '2023-10-01 08:00:00',
    pace: 5.45,  // 配速 (分钟/公里)
    heart_rate: 145, // 平均心率
    steps: 6450, // 步数
    elevation: 28, // 海拔变化(米)
    temperature: 22, // 温度(摄氏度)
    weather: '晴天',
    location: '城市公园',
  },
  {
    activity_id: 'a002',
    user_id: 'user001',
    type: '跑步',
    distance: 3.5,
    duration: 1200,
    calorie: 220,
    start_time: '2023-10-03 07:30:00',
    pace: 5.71,
    heart_rate: 150,
    steps: 4320,
    elevation: 15,
    temperature: 20,
    weather: '多云',
    location: '城市街道',
  },
  {
    activity_id: 'a003',
    user_id: 'user001',
    type: '骑行',
    distance: 15.8,
    duration: 2400,
    calorie: 450,
    start_time: '2023-10-05 17:00:00',
    pace: 0,
    heart_rate: 135,
    steps: 0,
    elevation: 120,
    temperature: 24,
    weather: '晴天',
    location: '郊外公路',
  },
  {
    activity_id: 'a004',
    user_id: 'user002',
    type: '游泳',
    distance: 1.2,
    duration: 1500,
    calorie: 280,
    start_time: '2023-10-07 19:00:00',
    pace: 20.83,
    heart_rate: 125,
    steps: 0,
    elevation: 0,
    temperature: 28,
    weather: '室内',
    location: '游泳馆',
  },
  {
    activity_id: 'a005',
    user_id: 'user002',
    type: '跑步',
    distance: 6.7,
    duration: 2100,
    calorie: 380,
    start_time: '2023-10-10 06:45:00',
    pace: 5.22,
    heart_rate: 155,
    steps: 8250,
    elevation: 45,
    temperature: 18,
    weather: '小雨',
    location: '城市公园',
  },
  {
    activity_id: 'a006',
    user_id: 'user003',
    type: '骑行',
    distance: 20.3,
    duration: 3000,
    calorie: 520,
    start_time: '2023-10-12 16:30:00',
    pace: 0,
    heart_rate: 140,
    steps: 0,
    elevation: 200,
    temperature: 22,
    weather: '多云',
    location: '山地公路',
  },
  {
    activity_id: 'a007',
    user_id: 'user003',
    type: '跑步',
    distance: 4.1,
    duration: 1450,
    calorie: 260,
    start_time: '2023-10-15 07:15:00',
    pace: 5.88,
    heart_rate: 148,
    steps: 5100,
    elevation: 12,
    temperature: 16,
    weather: '晴天',
    location: '城市街道',
  },
  {
    activity_id: 'a008',
    user_id: 'user004',
    type: '力量训练',
    distance: 0,
    duration: 3600,
    calorie: 420,
    start_time: '2023-10-18 18:00:00',
    pace: 0,
    heart_rate: 130,
    steps: 2200,
    elevation: 0,
    temperature: 25,
    weather: '室内',
    location: '健身房',
  },
  {
    activity_id: 'a009',
    user_id: 'user005',
    type: '瑜伽',
    distance: 0,
    duration: 2700,
    calorie: 180,
    start_time: '2023-10-20 07:00:00',
    pace: 0,
    heart_rate: 90,
    steps: 0,
    elevation: 0,
    temperature: 22,
    weather: '室内',
    location: '瑜伽馆',
  },
  {
    activity_id: 'a010',
    user_id: 'user004',
    type: '跑步',
    distance: 10.2,
    duration: 3600,
    calorie: 650,
    start_time: '2023-10-22 08:30:00',
    pace: 5.88,
    heart_rate: 162,
    steps: 12600,
    elevation: 65,
    temperature: 15,
    weather: '晴天',
    location: '公园跑道',
  },
  {
    activity_id: 'a011',
    user_id: 'user003',
    type: '游泳',
    distance: 1.8,
    duration: 2400,
    calorie: 350,
    start_time: '2023-10-25 19:30:00',
    pace: 22.22,
    heart_rate: 132,
    steps: 0,
    elevation: 0,
    temperature: 28,
    weather: '室内',
    location: '游泳馆',
  },
  {
    activity_id: 'a012',
    user_id: 'user002',
    type: '骑行',
    distance: 25.5,
    duration: 4500,
    calorie: 680,
    start_time: '2023-10-28 15:00:00',
    pace: 0,
    heart_rate: 145,
    steps: 0,
    elevation: 320,
    temperature: 20,
    weather: '多云',
    location: '山地公路',
  },
  {
    activity_id: 'a013',
    user_id: 'user001',
    type: '跑步',
    distance: 7.8,
    duration: 2700,
    calorie: 490,
    start_time: '2023-10-30 06:30:00',
    pace: 5.77,
    heart_rate: 158,
    steps: 9600,
    elevation: 50,
    temperature: 14,
    weather: '晴天',
    location: '郊外跑道',
  },
  {
    activity_id: 'a014',
    user_id: 'user005',
    type: '健走',
    distance: 5.2,
    duration: 3600,
    calorie: 280,
    start_time: '2023-11-01 16:00:00',
    pace: 11.54,
    heart_rate: 115,
    steps: 6800,
    elevation: 35,
    temperature: 16,
    weather: '多云',
    location: '城市公园',
  },
  {
    activity_id: 'a015',
    user_id: 'user004',
    type: '力量训练',
    distance: 0,
    duration: 4500,
    calorie: 520,
    start_time: '2023-11-03 19:00:00',
    pace: 0,
    heart_rate: 135,
    steps: 3200,
    elevation: 0,
    temperature: 24,
    weather: '室内',
    location: '健身房',
  }
];

/**
 * 获取用户列表
 */
export const getUsers = async (params = {}) => {
  try {
    // 使用后端API获取用户
    // const response = await apiClient.get('/users');
    
    // 临时使用模拟数据，当后端API就绪后再切换
    return {
      data: mockUsers,
      total: mockUsers.length
    };
  } catch (error) {
    console.error('获取用户列表失败:', error);
    // 返回模拟数据作为降级处理
    return {
      data: mockUsers,
      total: mockUsers.length
    };
  }
};

// 获取所有用户活动数据
export const getUserActivities = async (userId, params = {}) => {
  try {
    const queryParams = {
      startDate: formatDateForApi(params.startDate),
      endDate: formatDateForApi(params.endDate)
    };
    
    if (userId) {
      queryParams.userId = userId;
    }
    
    // 构建URL查询参数
    const queryString = Object.entries(queryParams)
      .filter(([_, value]) => value !== null && value !== undefined)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');
    
    const response = await apiClient.get(`/activities${queryString ? '?' + queryString : ''}`);
    
    return {
      data: response.data,
      total: response.data.length
    };
  } catch (error) {
    console.error('获取用户活动数据失败:', error);
    throw error;
  }
};

// 获取用户活动统计数据
export const getUserActivityStats = async (userId, params = {}) => {
  try {
    if (!userId) {
      // 如果没有用户ID，返回所有类型的统计
      const platformResponse = await getPlatformStats(params);
      // 转换格式以匹配之前的接口结构
      const result = {};
      
      // 从类型分布中创建统计数据
      if (platformResponse && platformResponse.typeDistribution) {
        platformResponse.typeDistribution.forEach(item => {
          result[item.type] = {
            count: item.count,
            totalDistance: item.distance || item.totalDistance || (item.count * 3.5), // 确保有距离数据
            totalDuration: item.duration || item.totalDuration || (item.count * 1800), // 确保有时长数据
            totalCalorie: item.calorie || item.totalCalorie || (item.count * 250), // 确保有卡路里数据
            avgHeartRate: item.avgHeartRate || 140,
            totalHeartRateReadings: item.totalHeartRateReadings || item.count,
            maxHeartRate: item.maxHeartRate || 180,
            totalSteps: item.totalSteps || (item.count * 4000),
            totalElevation: item.totalElevation || (item.count * 20),
            activities: []
          };
        });
      }
      
      return result;
    }
    
    // 有用户ID，获取该用户的统计
    const queryParams = {
      userId,
      startDate: formatDateForApi(params.startDate),
      endDate: formatDateForApi(params.endDate)
    };
    
    // 构建URL查询参数
    const queryString = Object.entries(queryParams)
      .filter(([_, value]) => value !== null && value !== undefined)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');
    
    try {
      const response = await apiClient.get(`/activities/stats?${queryString}`);
      
      // 检查返回的数据结构是否为日期格式
      const responseData = response.data;
      
      // 如果数据是按日期格式返回的，需要转换为按活动类型分组
      if (responseData && typeof responseData === 'object' && Object.keys(responseData).length > 0) {
        const firstKey = Object.keys(responseData)[0];
        // 检查第一个键是否类似日期格式 (YYYY-MM-DD)
        const isDateFormat = /^\d{4}-\d{2}-\d{2}$/.test(firstKey);
        
        if (isDateFormat) {
          console.log('检测到按日期分组的数据，进行转换');
          return convertDateStatsToTypeStats(responseData);
        }
      }
      
      return responseData;
    } catch (error) {
      console.error('API请求失败，使用模拟数据:', error);
      
      // 使用与用户提供的格式类似的模拟数据
      const mockDateData = {
        "2025-02-18": {
          "count": 38,
          "totalDistance": 587.8,
          "totalDuration": 2544,
          "totalCalorie": 24838,
          "uniqueUserCount": 31
        },
        "2025-02-19": {
          "count": 42,
          "totalDistance": 623.5,
          "totalDuration": 2780,
          "totalCalorie": 26540,
          "uniqueUserCount": 35
        }
      };
      
      // 转换为需要的格式
      return convertDateStatsToTypeStats(mockDateData);
    }
  } catch (error) {
    console.error('获取用户活动统计数据失败:', error);
    throw error;
  }
};

// 将日期格式的统计数据转换为活动类型格式
const convertDateStatsToTypeStats = (dateStats) => {
  // 定义活动类型及其分配比例
  const typeDistribution = {
    "run": 0.25,   // 跑步 25%
    "walk": 0.30,  // 步行 30%
    "bike": 0.25,  // 骑行 25%
    "swim": 0.20   // 游泳 20%
  };
  
  // 初始化结果对象
  const result = {};
  Object.keys(typeDistribution).forEach(type => {
    result[type] = {
      count: 0,
      totalDistance: 0,
      totalDuration: 0,
      totalCalorie: 0,
      avgHeartRate: 140,
      totalHeartRateReadings: 0,
      maxHeartRate: 180,
      totalSteps: 0,
      totalElevation: 0,
      activities: []
    };
  });
  
  // 汇总所有日期数据
  let totalCount = 0;
  let totalDistance = 0;
  let totalDuration = 0;
  let totalCalorie = 0;
  
  Object.values(dateStats).forEach(dayData => {
    totalCount += dayData.count || 0;
    totalDistance += dayData.totalDistance || 0;
    totalDuration += dayData.totalDuration || 0;
    totalCalorie += dayData.totalCalorie || 0;
  });
  
  // 按比例分配到各活动类型
  Object.keys(typeDistribution).forEach(type => {
    const ratio = typeDistribution[type];
    result[type].count = Math.round(totalCount * ratio);
    result[type].totalDistance = totalDistance * ratio;
    result[type].totalDuration = totalDuration * ratio;
    result[type].totalCalorie = totalCalorie * ratio;
    result[type].totalSteps = Math.round(totalCount * ratio * 4000);
    result[type].totalElevation = Math.round(totalCount * ratio * 20);
    result[type].totalHeartRateReadings = result[type].count;
  });
  
  console.log('转换后的活动类型数据:', result);
  return result;
};

// 获取活动时间趋势数据
export const getActivityTimeTrend = async (userId, params = {}) => {
  try {
    const queryParams = {
      userId,
      startDate: formatDateForApi(params.startDate),
      endDate: formatDateForApi(params.endDate)
    };
    
    // 构建URL查询参数
    const queryString = Object.entries(queryParams)
      .filter(([_, value]) => value !== null && value !== undefined)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');
    
    const response = await apiClient.get(`/activities/trends?${queryString}`);
    return response.data;
  } catch (error) {
    console.error('获取活动时间趋势数据失败:', error);
    throw error;
  }
};

// 获取训练强度分布
export const getTrainingIntensity = async (userId, params = {}) => {
  try {
    const queryParams = {
      userId,
      startDate: formatDateForApi(params.startDate),
      endDate: formatDateForApi(params.endDate)
    };
    
    // 构建URL查询参数
    const queryString = Object.entries(queryParams)
      .filter(([_, value]) => value !== null && value !== undefined)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');
    
    const response = await apiClient.get(`/activities/intensity?${queryString}`);
    return response.data;
  } catch (error) {
    console.error('获取训练强度分布失败:', error);
    throw error;
  }
};

// 获取运动位置热度
export const getActivityLocations = async (userId, params = {}) => {
  try {
    const queryParams = {
      userId,
      startDate: formatDateForApi(params.startDate),
      endDate: formatDateForApi(params.endDate)
    };
    
    // 构建URL查询参数
    const queryString = Object.entries(queryParams)
      .filter(([_, value]) => value !== null && value !== undefined)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');
    
    const response = await apiClient.get(`/activities/locations?${queryString}`);
    return response.data;
  } catch (error) {
    console.error('获取运动位置热度失败:', error);
    throw error;
  }
};

// 获取用户活动类型分布
export const getUserTypeDistribution = async (params = {}) => {
  try {
    const queryParams = {
      startDate: formatDateForApi(params.startDate),
      endDate: formatDateForApi(params.endDate)
    };
    
    // 构建URL查询参数
    const queryString = Object.entries(queryParams)
      .filter(([_, value]) => value !== null && value !== undefined)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');
    
    const response = await apiClient.get(`/activities/type-distribution?${queryString}`);
    return response.data;
  } catch (error) {
    console.error('获取用户活动类型分布失败:', error);
    throw error;
  }
};

// 获取平台整体数据统计
export const getPlatformStats = async (params = {}) => {
  try {
    const queryParams = {
      startDate: formatDateForApi(params.startDate),
      endDate: formatDateForApi(params.endDate)
    };
    
    // 构建URL查询参数
    const queryString = Object.entries(queryParams)
      .filter(([_, value]) => value !== null && value !== undefined)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');
    
    const response = await apiClient.get(`/activities/platform-stats?${queryString}`);
    return response.data;
  } catch (error) {
    console.error('获取平台整体数据统计失败:', error);
    
    // 如果接口报错，返回模拟数据结构
    // 为每种运动类型添加完整的统计信息
    const mockTypeDistribution = [
      { type: "run", count: 3664, totalDistance: 18402, totalDuration: 5412000, totalCalorie: 967450 },
      { type: "walk", count: 3885, totalDistance: 12800, totalDuration: 4300800, totalCalorie: 620500 },
      { type: "bike", count: 3741, totalDistance: 45240, totalDuration: 7482000, totalCalorie: 896400 },
      { type: "swim", count: 3678, totalDistance: 7356, totalDuration: 4781400, totalCalorie: 735600 }
    ];
    
    return {
      summary: {
        totalActivities: 14968,
        totalDistance: 184403,
        totalDuration: 22082400,
        totalCalorie: 8031891,
        uniqueUsers: 450
      },
      dailyStats: {
        '2023-10-01': { count: 120, distance: 950, duration: 158000, calorie: 24500 },
        '2023-10-02': { count: 135, distance: 1080, duration: 170000, calorie: 27800 }
      },
      activeUsersByDate: [
        { date: '2023-10-01', activeUsers: 80 },
        { date: '2023-10-02', activeUsers: 95 }
      ],
      typeDistribution: mockTypeDistribution
    };
  }
};